const cron = require('node-cron');
const Log = require('ee-core/log');
const Services = require('ee-core/services');
const Addon = require('ee-core/addon');
const _ = require('lodash');

/**
 * example插件
 * @class
 */
class CronAddon {

  isRunZc = 0
  isRunArt = 0

  // 自动注入 app 对象
  constructor(app) {
    this.app = app;
  }
  // 定义任务

  create(){
    Log.info('[addon:cron] load')
    const sendEmail = () => {
      this.zc()      
      this.art()      
    };
      // 任务调度
    const job = cron.schedule('* * * * *', sendEmail, {
      scheduled: false,
      timezone: 'Asia/Shanghai',
    })
    job.start()
  }
  //采集专场和拍品
  async zc(){
    if(this.isRunZc == 1) {
      Log.info('[addon:cron] ZC正在运行，关闭当前')
      return
    }
    this.isRunZc = 1
    try{
      const zcs = await Services.get('zc').list({status: 1}, 1)
      Log.info('专场:' + zcs.length)
      for(var i in zcs){
        var zc = zcs[i]
        var auction = await Services.get('auction').show(zc.auction_id)
        if(!auction)continue
        await Addon.get('collect').collectZc(auction, zc, 1)
      }
      this.isRunZc = 0
    }catch(e){
      this.isRunZc = 0
    }
    
    
  }
  async art(){
    if(this.isRunArt == 1) {
      Log.info('[addon:cron] ART正在运行，关闭当前')
      return
    }
    this.isRunArt = 1
    try{
      await Addon.get('collect').postArtsCollect()
      this.isRunArt = 0
    }catch(e){
      console.log(e)
      this.isRunArt = 0
    }
  }
}

CronAddon.toString = () => '[class CronAddon]';
module.exports = CronAddon;